# -*- coding: utf-8 -*-

from osv import fields,osv
from osv.orm import browse_record
import tools
from functools import partial
import pytz
import pooler
from tools.translate import _
from service import security
import netsvc
import datetime

class aas_course_register(osv.TransientModel):
    _name = 'aas.course.register'
    _columns = {
        'register_id': fields.many2one('aas.register.courses', string='Registration'),
        'name': fields.char('Mã lớp môn học', size=64),
        'lecturer': fields.char('Giảng viên', size=64),
        'subject': fields.char('Môn học', size=64),
        'total_credit': fields.integer('Tổng số tín chỉ'),
        'day': fields.selection((('mon', _('Thứ Hai')),
                                 ('tue', _('Thứ Ba')),
                                 ('wed', _('Thứ Tư')),
                                 ('thu', _('Thứ Năm')),
                                 ('fri', _('Thứ Sáu')),
                                 ('sat', _('Thứ Bảy')),
                                 ('sun', _('Chủ Nhật')),), string='Học vào'),
        'periods': fields.many2many('aas.period', 'aas_course_register_period_rel', 'course_id', 'period_id', 'Các ca học'), 
        'year': fields.many2one('aas.academic.year', string='Năm học'),
        'semester': fields.many2one('aas.academic.semester', string='Học kỳ'),
        'max_reg': fields.integer('Số lượng tối đa'),
        'cur_reg': fields.integer('Số lượng hiện tại'),
        'reason': fields.text('Nguyên nhân'),
    }
    _defaults = {
        'day': lambda *a: 'mon',
    }
    
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if view_type=='tree':
            if not context: context = {}
            error = context.get('error', 0)
            if error:
                year_obj = self.pool.get('aas.academic.year')
                view_id = year_obj.get_view_id(cr, uid, 'aas_course', 'aas_course_register_tree_view_error', context=context)
        result = super(aas_course_register, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
        return result
    
aas_course_register()

class aas_register_courses(osv.TransientModel):
    _name = 'aas.register.courses'
    _columns = {
        'courses': fields.one2many('aas.course.register', 'register_id', string='Details', readonly=True),
        'courses_error': fields.one2many('aas.course.register', 'register_id', string='Details', readonly=True, context={'error': 1}),
    }
    
    def get_register_info(self, cr, uid, context=False):
        res = [[], []]
        if not context: context = {}
        ids = context.get('active_ids', [])
        if ids:
            course_obj = self.pool.get('aas.course.course')
            course_student_obj = self.pool.get('aas.course.student')
            
            error = _('Không thể đăng ký các lớp môn học thuộc các danh sách khác nhau cùng một lúc!')
            course_list = False
            invalid_ids = []
            for obj in course_obj.browse(cr, uid, ids, context=context):
                if not course_list: course_list = obj.list_id
                else:
                    if course_list != obj.list_id:
                        print course_list.id, obj.list_id.id 
                        invalid_ids = ids
                        break
            if invalid_ids:
                for id in invalid_ids:
                    res[1].append([id, error])
            else:
                valid_ids = course_obj.search(cr, uid, [('id', 'in', ids), ('list_id.state', 'in', ('register_wait',))])
                invalid_ids = list(set(ids).difference(set(valid_ids)))
                error = _('Lớp môn học này chưa cho phép đăng ký!')
                for id in invalid_ids:
                    res[1].append([id, error])
                
                if valid_ids:
                    invalid_ids = []
                    
                    error = _('Lớp môn học này đã được đăng ký đủ số lượng!')
                    for obj in course_obj.browse(cr, uid, valid_ids, context=context):
                        if obj.cur_reg >= obj.max_reg:
                            res[1].append([obj.id, error])
                            invalid_ids.append(obj.id)
                    
                    valid_ids = list(set(valid_ids).difference(set(invalid_ids)))
                    if valid_ids:
                        error = _('Không thể đăng ký quá số tín chỉ tối đa cho phép!')
                        cur_no = 0
                        invalid_ids = []
                        for obj in course_obj.browse(cr, uid, valid_ids, context=context):
                            cur_no += obj.total_credit
                            if cur_no > course_list.max_number_of_credits:
                                invalid_ids.append(obj.id)
                                res[1].append([obj.id, error])
                        
                        valid_ids = list(set(valid_ids).difference(set(invalid_ids)))
                        if valid_ids:
                            error = _('Bạn đã đăng ký lớp môn học này!')
                            invalid_ids = []
                            for id in valid_ids:
                                temp_ids = course_student_obj.search(cr, uid, [('course_id', '=', id), ('student_id', '=', uid)], context=context)
                                if temp_ids:
                                    invalid_ids.append(id)
                                    res[1].append([id, error])
                            
                            valid_ids = list(set(valid_ids).difference(set(invalid_ids)))
                            for id in valid_ids:
                                res[0].append(id)
        return res
    
    def check_able_to_register_course(self, cr, uid, course):
        return True
    
#    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
#        if view_type=='form':
#            if not context: context = {}
#            active_ids = context.get('active_ids', [])
#            if active_ids:
#                register_info = self.get_register_info(cr, uid, context=context)
#                year_obj = self.pool.get('aas.academic.year')
#                view_id = year_obj.get_view_id(cr, uid, 'aas_course', 'aas_register_courses_form_error', context=context)
#        result = super(aas_register_courses, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
#        return result
    
    def default_get(self, cr, uid, fields, context=False):
        res = super(aas_register_courses, self).default_get(cr, uid, fields, context=context)
        ids = context.get('active_ids', [])
        self.courses_ids = []
        if ids:
            course_obj = self.pool.get('aas.course.course')
            
            register_obj = self.pool.get('aas.course.register')
            
            all_courses = []
            all_courses_invalid = []
            
            register_info = self.get_register_info(cr, uid, context=context)
            
            if register_info[0]:
                for course in course_obj.browse(cr, uid, register_info[0], context=context):
                    self.courses_ids.append(course.id)
                    periods = []
                    for period in course.periods:
                        periods.append(period.id)
                    data = {
                        'name': course.name,
                        'lecturer': course.lec_id and course.lec_id.name or '',
                        'subject': course.subject_id.name,
                        'total_credit': course.total_credit,
                        'day': course.day,
                        'max_reg': course.max_reg,
                        'cur_reg': course.cur_reg,
                        'periods': periods,
                        'year': course.academic_year.id,
                        'semester': course.academic_semester.id,
                    }
                    all_courses.append(data)
            
            if register_info[1]:
                for (id, reason) in register_info[1]:
                    course = course_obj.browse(cr, uid, id, context=context)
                    periods = []
                    for period in course.periods:
                        periods.append(period.id)
                    data = {
                        'name': course.name,
                        'lecturer': course.lec_id and course.lec_id.name or '',
                        'subject': course.subject_id.name,
                        'total_credit': course.total_credit,
                        'day': course.day,
                        'max_reg': course.max_reg,
                        'cur_reg': course.cur_reg,
                        'periods': periods,
                        'year': course.academic_year.id,
                        'semester': course.academic_semester.id,
                        'reason': reason,
                    }
                    all_courses_invalid.append(data)
            
            res.update({'courses': all_courses, 'courses_error': all_courses_invalid})            
        return res
    
    
    def register_courses(self, cr, uid, ids, context=False):
        if self.courses_ids:
            course_student_obj = self.pool.get('aas.course.student')
            for id in self.courses_ids:
                data = {
                    'course_id': id,
                    'student_id': uid,
                    'time_register': datetime.datetime.now(),
                }
                course_student_obj.create(cr, 1, data, context=context)
        return {
            'name': 'Thông tin đăng ký học phần cá nhân',
            'view_type': 'form', 
            'view_mode': 'form', 
            'res_model': 'aas.personal.enrollment',
            'type': 'ir.actions.act_window', 
            'target': 'new',
        }
    
aas_register_courses()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
